package com.bodacn.andontv;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;

import android.view.inputmethod.InputMethodManager;

import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.serialport.SerialPort;
import com.android.serialport.SerialPortFinder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapFault;
import org.ksoap2.transport.HttpResponseException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.InetAddress;
import java.net.MulticastSocket;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {
    private final static String TAG = MainActivity.class.getSimpleName();
    private final static int MSG_Switch=1001,MSG_Init=1002,MSG_Trans=1003,MSG_SwitchAndon=1004,MSG_SerialRecOK=1005,MSG_GetDataOver=1006,MSG_CheckNetWork=1007;
    boolean hasAndonFragment=false;//是否包含安东，无安东不蓝牙
    int andonDelaySec=2;//安东显示时间;
    String portName="/dev/ttyS4";
    //String portName="/dev/ttySAC0";
    //界面控件;
    private LinearLayout mainLinerLayout,liner_debugInfo,liner_debugBtn,bottomLayout;
    private Button OneBtn,TwoBtn,ThreeBtn,FourBtn,CallBtn,MenuBtn,AndonBtn,ClearBtn,StudyBtn;
    private TextView tv_boardNo,tv_hintInfo;
    private TextView tv_result,tv_data,tv_portname,tv_portstate;
    private ProgressBar pgbar_wait;
    FrameLayout mFragmentContainer;
    static boolean receiveFlag=false;
    static SerialPort mSerialPort = null;
    static FileInputStream mInputStream = null;
    String PrRecData;
    boolean showDebug=false ;//是否显示调试;
    //存放当前FragmentM
    private Fragment mContent;
    private Toast curToast;
    private Timer  netTimer;
    private TimerTask netTimeTask;
    Drawable mainBackgroup=null;
    private FragmentManager fragmentManager=getSupportFragmentManager();
    /* 保存解析的XML信息 */
    HashMap<String, String> ServerConfig;

    class FragmentStruct{
        Fragment frgmt;
        String ident;
    }
    private List<FragmentStruct> mFragments=new ArrayList<FragmentStruct>();//fragment列表;
    class CallKeyDefine{
        String ConType;
        String ConValue;
        String ConKey;
        String CallType;
        String CallColor;
        String FontColor;
        String NeedCheck;
        String LightCon;
    }
    private List<CallKeyDefine> mCallKeys=new ArrayList<CallKeyDefine>();//呼叫类型定义;

    public int curFragmentIndex = 0;//当前显示页面;
    public static final int msgOneFragment = 801;//One;
    public static final int msgTwoFragment=802;//Two;
    public static final int msgThreeFragment=803;//Three;
    public static final int msgFourFragment=804;//Four;
    public static final int msgFiveFragment=805;//Five;
    public static final int MSG_GetAndonListOver=806;//Five;

    public static String PushTime="RUN";//暂停
    String AutoLoop="YES";//自动循环;
    JSONArray curUserPower,AndonList,CallList;
    //初始化定时器;
    private Timer timer,uploadTimer;
    private TimerTask timetask,uploadTimeTask;
    //时间暂停执行;
    private boolean PasueSwitch =false;
    private static int runCount=0;//计数器，超过一定的次数，就刷新数据;
    //全局变量
    private static final int pageItemCount = 3;//每页显示内容;
    //刷新间隔
    int switchSpaceSec=30;//多个页面切换间隔;
    int refreshSpaceSec = 5;//页面刷新间隔(考虑手工设置);
    int switchCount=5;//翻页次数(考虑手工设置);
    JSONArray tmpJsonArray;//用于存储WebService返回的结果;
    //服务器地址
    String serviceUrl="http://172.16.100.202:8000/";
    String serverUrlExt  = "/BDService.asmx?wsdl";
    //看板编号;
    private BasePopupWindow callPopupWindow;
    byte[] WriteBytes = new byte[20];
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;
    String sendHint="";
    private Context mContext;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> mParams=new HashMap<String,Object>();
    private Map<String,Object> tmpParams=new HashMap<String,Object>();
    public String receiveInfo="";
    /*接收广播端的socket*/
    private MulticastSocket ds;
    private int udpPort=40000;
    String multicastHost="224.0.0.1";//广播地址;
    InetAddress receiveAddress;
    //MQTT

    //---------------------------接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransAndonParamsListener{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransAndonParamsListener transAndonParamsListener;
    //3:写一个对外公开的方法setTransTwoParamsListener,供Fragment加接口监使用;
    public void setTransAndonParamsListener(OnTransAndonParamsListener transAndonParamsListener){
        this.transAndonParamsListener=transAndonParamsListener;
    }
    //---------------------------接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransOneParamsListener{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransOneParamsListener transOneParamsListener;
    //3:写一个对外公开的方法setTransOneParamsListener,供Fragment加接口监使用;
    public void setTransOneParamsListener(OnTransOneParamsListener transOneParamsListener){
        this.transOneParamsListener=transOneParamsListener;
    }
    //---------------------------接口申明及调用------------------------结束;

    //---------------------------接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransTwoParamsListener{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransTwoParamsListener transTwoParamsListener;
    //3:写一个对外公开的方法setTransTwoParamsListener,供Fragment加接口监使用;
    public void setTransTwoParamsListener(OnTransTwoParamsListener transTwoParamsListener){
        this.transTwoParamsListener=transTwoParamsListener;
    }

    //---------------------------接口申明及调用------------------------开始;
    //1:定义一个传参接口;
    public  interface OnTransStudyParamsListener{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String,Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransStudyParamsListener transStudyParamsListener;
    //3:写一个对外公开的方法setTransTwoParamsListener,供Fragment加接口监使用;
    public void setTransStudyParamsListener(OnTransStudyParamsListener transStudyParamsListener){
        this.transStudyParamsListener =transStudyParamsListener;
    }
    //---------------------------接口申明及调用------------------------结束;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=this;
        //创建目录;
        try{
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
        //创建数据库
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        //创建表;
        //DropAllTable();
        CreateDBTable();
        //初始化界面控件
        initView();
        //从本地获取安东设备列表;
        GetAndonList();
        GetConDefine();
        //获取屏幕信息
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        //接收广播
        System.out.println("启动接收线程--Over");
        new Thread(this).start();
        System.out.println("启动接收线程--Over");
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }



    //加载安东列表
    @SuppressLint("Range")
    private void GetAndonList() {
        System.out.println("GetAndonList---Enter");
        if (mainDB!=null) {
            System.out.println("GetAndonList---Enter:A");
            try {
                AndonList = new JSONArray("[]");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Cursor cur = mainDB.rawQuery("Select * from AndonList Group by ID", null);
            while (cur.moveToNext()) {
                JSONObject objectJSON = new JSONObject();
                try {
                    objectJSON.put("CallNo", cur.getString(cur.getColumnIndex("CallNo")));
                    objectJSON.put("CallAddr", cur.getString(cur.getColumnIndex("CallAddr")));
                    objectJSON.put("EmpName", cur.getString(cur.getColumnIndex("EmpName")));
                    objectJSON.put("MachType", cur.getString(cur.getColumnIndex("MachType")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                AndonList.put(objectJSON);
            }
            cur.close();
            System.out.println(AndonList);
        }
    }
    //加载安东列表
    @SuppressLint("Range")
    private void GetConDefine() {
        if (mainDB!=null) {
            Cursor cur = mainDB.rawQuery("Select * from ConDefine Group by ID", null);
            mCallKeys.clear();
            while (cur.moveToNext()) {
                //加表定义列表中
                CallKeyDefine KeyDefine=new CallKeyDefine();
                KeyDefine.ConType=cur.getString(cur.getColumnIndex("ConType"));
                KeyDefine.ConValue=cur.getString(cur.getColumnIndex("ConValue"));
                KeyDefine.ConKey=cur.getString(cur.getColumnIndex("ConKey"));
                KeyDefine.CallType=cur.getString(cur.getColumnIndex("CallType"));
                KeyDefine.CallColor=cur.getString(cur.getColumnIndex("CallColor"));
                KeyDefine.FontColor=cur.getString(cur.getColumnIndex("FontColor"));
                KeyDefine.NeedCheck=cur.getString(cur.getColumnIndex("NeedCheck"));
                KeyDefine.LightCon=cur.getString(cur.getColumnIndex("LightCon"));
                mCallKeys.add(KeyDefine);
            }
            cur.close();
        }
    }

    //加载安东列表
    private int GetCallCount() {
        if (mainDB!=null) {
            int rtn=0;
            Cursor cur = mainDB.rawQuery("Select * from CallList where CallState<2", null);
            rtn= cur.getCount();
            cur.close();
            return rtn;
        }
        return 0;
    }






    //用于接收线程消息，刷新界面;
    public Handler receiveHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            //置日期初始值;
            Date curDate = new Date(System.currentTimeMillis());
            String StartDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
            System.out.println("receiveHandle-----"+MainApplication.BoardNo+"--------------"+StartDateStr+":"+receiveInfo);
            if (receiveInfo.equals("ShowAndonFragment-"+MainApplication.BoardNo+":Refresh")==true){
                switchFragment(mContent,"AndonFragment");
            }
            if (receiveInfo.equals("ShowOneFragment-"+MainApplication.BoardNo+":Refresh")==true){
                switchFragment(mContent,"OneFragment");
            }
            if (receiveInfo.equals("ShowTwoFragment-"+MainApplication.BoardNo+":Refresh")==true){
                switchFragment(mContent,"TwoFragment");
            }
            if (receiveInfo.equals("ShowThreeFragment-"+MainApplication.BoardNo+":Refresh")==true){
                switchFragment(mContent,"ThreeFragment");
            }
            showPopWindows("001-测试呼叫","RED");
        }
    };

    //判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            try{
                mainDB.rawQuery("select EmpName from AndonList",null);
            } catch (Exception  e){
                System.out.println(e.getMessage());
                System.out.println("清除数据库表");
                DropAllTable();
            }
            //建表语句;
            System.out.println("CreateDBTable--------------Start");
            //呼叫定义
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS ConDefine (ID INTEGER PRIMARY KEY AUTOINCREMENT,ConType VARCHAR,ConValue VARCHAR,ConKey VARCHAR,CallType VARCHAR,CallColor VARCHAR,FontColor VARCHAR,NeedCheck VARCHAR,LightCon VARCHAR)");
            //设备表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS AndonList (ID INTEGER PRIMARY KEY AUTOINCREMENT,CallNo VARCHAR,CallAddr VARCHAR,EmpName VARCHAR,MachType VARCHAR)");
            //呼叫列表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS CallList (ID INTEGER PRIMARY KEY AUTOINCREMENT,CallID VARCHAR,CallTime VARCHAR,CallNo VARCHAR," +
                    "CallAddr VARCHAR,EmpName VARCHAR,CallType VARCHAR,CheckTime VARCHAR,OverTime VARCHAR,CallState int,StateInfo VARCHAR,UpLoad int default 0,CallColor VARCHAR,FontColor VARCHAR,NeedCheck VARCHAR,LightCon VARCHAR)");
            System.out.println("CreateDBTable--------------End");
        }
    }

    //获取当前时间;
    private String GetCurDateTime(){
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  curDate= sDateFormat.format(new java.util.Date());
        return curDate;
    }
    //删除数据库
    private void DropAllTable(){
        if (mainDB!=null) {
            Log.d("Delete","删除数据库！");
            mainDB.execSQL("DROP TABLE IF EXISTS ConDefine");
            mainDB.execSQL("DROP TABLE IF EXISTS CallList");
            mainDB.execSQL("DROP TABLE IF EXISTS AndonList");
        } else System.out.println("外部存储不可读写！");
    }
    //清除呼叫数据并重置自增长量;
    private  void clearCallList(){
        if (mainDB!=null) {
            Log.d("Delete","删除呼叫记录............");
            mainDB.execSQL("DELETE FROM CallList");
            mainDB.execSQL("UPDATE sqlite_sequence Set seq=0 where name='CallList'");

        }
    }
    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        byte recBuffer[]=new byte[128];
        int delayCount=0;
        while (true) {
            if ((mInputStream != null)&&(receiveFlag==true)) {
                try {
                    //防止数据分段;
                    try {
                        if (receiveFlag && (mInputStream.available() == 0)) {
                            Thread.sleep(10);
                            System.currentTimeMillis();
                            continue;
                        } else {
                            Thread.sleep(50);
                        }
                    } catch (InterruptedException e) {
                        Log.d("run()", "获取数据出错");
                        e.printStackTrace();
                    }
                    //检查是否有数据;
                    int size = 0;
                    if (receiveFlag == true) size = mInputStream.read(recBuffer);
                    if (size > 0 && receiveFlag) {
                        byte realBuffer[] = new byte[size];
                        for (int i = 0; i < size; i++) realBuffer[i] = recBuffer[i];
                        String realInfo = bytesToHexString(realBuffer, size);
                        Log.d("realInfo", realInfo);
                        Message msg_rec = new Message();
                        msg_rec.what = MSG_SerialRecOK;
                        Bundle bundle_rec = new Bundle();
                        bundle_rec.clear();
                        bundle_rec.putString("RecHex", realInfo);
                        bundle_rec.putInt("RecLen", size);
                        bundle_rec.putByteArray("RecBytes", realBuffer);
                        msg_rec.setData(bundle_rec);
                        mHandler.removeMessages(msg_rec.what);
                        mHandler.sendMessage(msg_rec);
                    }
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("onStart ---------------------------------1");

    }
    //显示弹窗
    private void showPopWindows(String paramCallInfo,String paramColor){
        int deviationX=300,deviationY=300;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        try {
            System.out.println("屏宽:" + dm.widthPixels);
            System.out.println("屏高:" + dm.heightPixels);
            //创建并初始化完成
            //创建并初始化完成
            if (callPopupWindow == null) {
                callPopupWindow = new BasePopupWindow(this);
                callPopupWindow.setWidth(dm.widthPixels - deviationX);
                callPopupWindow.setHeight(dm.heightPixels - deviationY);
            }
            //取视图
            View inflaterView = LayoutInflater.from(this).inflate(R.layout.andon_pop, null);
            LinearLayout linear_AndonPop = inflaterView.findViewById(R.id.linear_AndonPop);
            TextView tv_AndonPop = inflaterView.findViewById(R.id.tv_AndonPop);
            if (paramColor.toUpperCase().equals("RED") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_red));
            if (paramColor.toUpperCase().equals("BLUE") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_blue));
            if (paramColor.toUpperCase().equals("YELLOW") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_yellow));
            if (paramColor.toUpperCase().equals("GREEN") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_green));
            if (paramColor.toUpperCase().equals("REPEAT") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_repeat));
            tv_AndonPop.setText(paramCallInfo);
            //显示视图
            callPopupWindow.setContentView(inflaterView);
            callPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));//全透明背景
            callPopupWindow.setOutsideTouchable(false);
            callPopupWindow.setFocusable(true);
            callPopupWindow.viewSecond = andonDelaySec;//显示5秒，自定义类;
            if (mainLinerLayout != null)
                callPopupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER, 0, 0);
            //发送语间播报消息;
            if (transAndonParamsListener != null) {
                tmpParams.clear();
                tmpParams.put("ParamComm", "TTS");
                tmpParams.put("ParamText", paramCallInfo);
                transAndonParamsListener.TransParams(tmpParams);
            }
        }catch (Exception e){
            if (showDebug) displayData(e.getMessage());
        }

    }
    //从网络获取版本升级文件
    public void GetServerConfig(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetServerConfig","文件接收A:---"+serviceUrl);
                try {
                    ParseXmlService service = new ParseXmlService();
                    InputStream inStream = new URL(serviceUrl).openStream();
                    System.out.println("服务器配置文件获取成功....");
                    ServerConfig = service.parseXml(inStream);
                    System.out.println(ServerConfig);
                    System.out.println("服务器配置文件解析成功....");
                    return "OK";
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true) Log.d(TAG,"获取服务器配置文件异常,错误异常抛出！");
                return "NO";
            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr==null)||(rtnstr=="NO"))
                {
                    Toast.makeText(getApplicationContext(), "版本更新文件下载错误", Toast.LENGTH_LONG).show();
                    return;
                } else Log.d(TAG,"文件获取成功..");
                //判断版本是否相同;
                if (null != ServerConfig)
                {
                    MainApplication.ServerIP = ServerConfig.get("ServerIP");
                    MainApplication.UserName = ServerConfig.get("UserName");
                    MainApplication.Password = ServerConfig.get("Password");
                    MainApplication.DBName = ServerConfig.get("DBName");
                    DBUtil.ServerIP=MainApplication.ServerIP;
                    DBUtil.UserName=MainApplication.UserName;
                    DBUtil.Password=MainApplication.Password;
                    DBUtil.DBName=MainApplication.DBName;
                    //保存配置文件;
                    savePref();
                    String hintInfo="GetServerConfig:SQLAddr:"+MainApplication.ServerIP+" SQLUser:"+MainApplication.UserName+" SQLPsw:"+MainApplication.Password+" SQLDBName:"+MainApplication.DBName;
                    Log.i(TAG,hintInfo);
                    if (showDebug) tv_result.setText(hintInfo+"\r\n"+tv_result.getText().toString());
                }

            }
        }.execute(params);

    }


    //获取配置;
    private  void getPref(){
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        serviceUrl=sp.getString("ServiceURL",serviceUrl);
        MainApplication.BoardNo=sp.getString("BoardNo",MainApplication.BoardNo);
        MainApplication.TCP=sp.getString("TCP",MainApplication.TCP);
        //Fragment切换间隔;
        switchSpaceSec=Integer.parseInt(sp.getString("SwitchSpec","30"));
        //页面停留时间;
        refreshSpaceSec=Integer.parseInt(sp.getString("RefreshSpec","5"));
        //翻多少次页后就要刷新;
        switchCount=Integer.parseInt(sp.getString("SwitchCount","5"));
        //数据库配置
        MainApplication.ServerIP =sp.getString("SQLAddr","");
        MainApplication.UserName=sp.getString("SQLUser","");
        MainApplication.Password=sp.getString("SQLPsw","");
        MainApplication.DBName=sp.getString("SQLDBName","");
        //数据连接类赋值;
        DBUtil.ServerIP=MainApplication.ServerIP;
        DBUtil.UserName=MainApplication.UserName;
        DBUtil.Password=MainApplication.Password;
        DBUtil.DBName=MainApplication.DBName;
        String hintInfo="GetServerConfig:SQLAddr:"+MainApplication.ServerIP+" SQLUser:"+MainApplication.UserName+" SQLPsw:"+MainApplication.Password+" SQLDBName:"+MainApplication.DBName;
        Log.i(TAG,hintInfo);
        if (showDebug) tv_result.setText(hintInfo+"\r\n"+tv_result.getText().toString());
    }


    //启动定时器;
    private void checkNetTimer(){
        if (netTimer ==null) {
            netTimer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (netTimeTask == null) {
                netTimeTask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_CheckNetWork;
                        mHandler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            netTimer.schedule(netTimeTask, 1000, 1000);
        }
    }
    //停止计时器;
    private void stopCheckTimer(){
        if (netTimer != null) {
            netTimer.cancel();
            netTimer = null;
        }
        if (netTimeTask != null) {
            netTimeTask.cancel();
            netTimeTask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }

    private void savePref(){
        //登陆成功后保存配置;
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("SQLAddr", MainApplication.ServerIP);
        set_editor.putString("SQLUser", MainApplication.UserName);
        set_editor.putString("SQLPsw", MainApplication.Password);
        set_editor.putString("SQLDBName", MainApplication.DBName);
        set_editor.commit();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //读取配置文件;
        getPref();
        //置版本号;
        try {
            tv_boardNo.setText("编号:"+MainApplication.BoardNo+"[Ver:"+getVersionName()+"]");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e(TAG,"-----------------------------------------onResume-----------------------------------------");
        checkNetTimer();
        //开串口
        String serials[]=new SerialPortFinder().getAllDevicesPath();
        String haveSerial="N";
        for (int i=0;i<serials.length;i++){
            System.out.println("serials["+i+"]:"+serials[i]);
            if (serials[i].equals(portName)){
                //openSrialPort();
                Toast.makeText(mContext,"串口"+portName+"已打开!",Toast.LENGTH_LONG).show();
                haveSerial="Y";
                System.out.println("打开串口"+portName);
            }
        }
        if (haveSerial.equals("N")) Toast.makeText(mContext,"串口"+portName+"未找到!",Toast.LENGTH_LONG).show();
        /*启动service*/
        System.out.println("MainApplication.TCP:"+MainApplication.TCP);
        System.out.println("MainApplication.port:"+MainApplication.Port);


    }

    public void GetWebStyleImage(String serviceUrl, final String fileName, Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("fileName",fileName);
        params.put("paramMap",paramMap);
        System.out.println("加载网络背景图片:"+serviceUrl+" fileName:"+fileName);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,Bitmap>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Bitmap doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                Log.d("GetWebImage","图片接收A:---"+serviceUrl);
                String fileName= (String) params[0].get("fileName");
                Log.d("GetWebImage","图片接收B:---"+fileName);
                Bitmap bitmap = null;
                try {
                    //加载一个网络图片
                    InputStream is = new URL(serviceUrl).openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    //保存图片;
                    saveBitmap(bitmap,fileName);
                    return bitmap;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (Exception e){
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true){
                    Log.d("msg","背景图片未找到！");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bm) {
                super.onPostExecute(bm);
                //这部分主要用于UI更新;
                Log.d("msg","图片接收成功。。。。。。。。");
                displayData("背景图片接收成功！");
                //将图片作为变量
                if (bm!=null) {
                    mainBackgroup = new BitmapDrawable(getResources(), bm);
                    mainLinerLayout.setBackground(mainBackgroup);
                }
                //发送消息，变换图片;
            }
        }.execute(params);

    }

    //获取本地图片;
    public  Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis=null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            }finally{
                if(fis!=null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis=null;
                }
            }
        } else {
            return null;
        }
    }



    /** 保存文件 */
    public void saveBitmap(Bitmap bm,String fileName) {
        String imgfilepath=this.getCacheDir().toString();
        Log.d("saveBitmap","imgfilepath:"+imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG")>0) bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG")>0)||(fileName.toUpperCase().indexOf("JPEG")>0)) bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //显示看板页脚;
        //bottomLayout.setVisibility(View.VISIBLE);
        curToast.setText("按键:"+keyCode+" ");
        curToast.show();
        if ((keyCode==21)||(keyCode==22))
        {
            if (keyCode==21) {
                if (curFragmentIndex>0) curFragmentIndex--;
                switchFragment(mContent,mFragments.get(curFragmentIndex).ident);
            }
            if (keyCode==22){
                if (curFragmentIndex<mFragments.size()-1) curFragmentIndex++;
                switchFragment(mContent,mFragments.get(curFragmentIndex).ident);
            }
            //curToast.setText("按键:"+keyCode+" 左右翻页");
            //curToast.show();
            return false;
        } else
        if (keyCode==168)
        {
            if (PushTime=="RUN") PushTime="PUSH";else PushTime="RUN";
            //curToast.setText("按键:"+keyCode+" 翻页:"+PushTime);
            //curToast.show();
            return false;
        } else {
            if (keyCode==8) MenuBtn.performClick();
            if (keyCode==9) AndonBtn.performClick();
            if (keyCode==10) ClearBtn.performClick();
            if (keyCode==11) StudyBtn.performClick();

            //Toast.makeText(this,"按键:"+keyCode,Toast.LENGTH_SHORT).show();
        }

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) {
            showTips();
            return false;
        }else
        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
            stopTimer();
            showMemu();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("系统提示").setMessage("您确定要退出程序吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                }).setNegativeButton("取消",

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.testBtn:
                studyMessage("12345678");
                break;
            case R.id.CallBtn:

                showPopWindows("测试", "RED");
                String uuid = UUID.randomUUID().toString().toUpperCase();
                mainDB.execSQL("Insert into CallList(CallID,CallTime,CallNo,EmpName,CallAddr,CallType,CallState,StateInfo,NeedCheck,CallColor,FontColor,LightCon) values(?,?,?,?,?,?,?,?,?,?,?,?)",
                        new Object[]{uuid, GetCurDateTime(), "1","测试", "2", "维修", 0, 1,1, "#FF0000","#00FF00",0});
                //发消息通知切换到呼叫界面
                Message message = new Message();
                message.what = MSG_SwitchAndon;
                mHandler.removeMessages(message.what);
                mHandler.sendMessage(message);
                break;
            case R.id.MenuBtn:
                stopTimer();
                showMemu();
                break;
            case R.id.AndonBtn:
                LoadAndonList(MainApplication.BoardNo);
                LoadConDefine(MainApplication.BoardNo);
                break;
            case R.id.OneBtn:
                showPopWindows("报到", "Green");
                mainDB.execSQL("update CallList set CallState=2 ");

                break;
                /*
                if (mFragments.size()>0) {
                    curFragmentIndex = 0;
                    switchFragment(mContent, mFragments.get(curFragmentIndex).ident);
                }
                break;*/
            case R.id.TwoBtn:
                if (mFragments.size()>1) {
                    curFragmentIndex = 1;
                    switchFragment(mContent, mFragments.get(curFragmentIndex).ident);
                }
                break;
            case R.id.ThreeBtn:
                if (mFragments.size()>2) {
                    curFragmentIndex = 2;
                    switchFragment(mContent, mFragments.get(curFragmentIndex).ident);
                }
                break;
            case R.id.FourBtn:
                if (mFragments.size()>3) {
                    curFragmentIndex = 3;
                    switchFragment(mContent, mFragments.get(curFragmentIndex).ident);
                }
                break;
            case R.id.ClearBtn:
                clearCallList();
                //发消息,启动某个Fragment Start;
                Message message1 = new Message();
                message1.what = MSG_SwitchAndon;
                mHandler.removeMessages(message1.what);
                mHandler.sendMessage(message1);
                break;
            case R.id.StudyBtn:
                if (curUserPower==null) return;
                Toast.makeText(mContext,curUserPower.toString(),Toast.LENGTH_LONG).show();
                for (int i=0;i<curUserPower.length();i++){
                    if (curUserPower.optJSONObject(i).has("Study"))
                        switchFragment(mContent, "StudyFragment");
                };
                break;
            default:
                break;
        }
    }

    /**
     * 计算CRC16校验码*
     * @param bytes 字节数组
     * @return {@linkString} 校验码
     * @since 1.0
     */
    public static int getCRC(byte[] bytes,int len) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < len; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return CRC;
    }
    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    private static String bytesToHexString(byte[] bytes,int size) {
        StringBuilder sb = new StringBuilder();
        //for (int i = 0; i < bytes.length; i++) {
        for (int i = 0; i < size; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]).toUpperCase();
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex+" ");
        }
        return sb.toString();
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBitArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte)(b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }
    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    public static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个进制字节
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        b = null;
        return b2;
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] HexStrToBytes(String str) {
        if ((str.trim().length() % 2) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }
        System.out.println("HexStrToBytes:"+str);
        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    //接收到呼叫按钮;
    private void studyCall(byte[] paramBytes){
        String CallAddr="",CallNo="",EmpName="",CallType="",FuncHex,NeedCheck="Y",CallColor,FontColor,LightCon;
        System.out.println(paramBytes);
        if (showDebug) displayData("Enter1"+paramBytes.length+"\r\n"+tv_result.getText().toString());
        if (paramBytes.length==9) {
            //ConKey,ConType,NeedCheck;
            String[] rtn=new String[]{"unknow","unknow","unknow","RED","#0000FF","00"};
            String TmpStr=bytesToHexString(paramBytes,paramBytes.length);
            TmpStr=TmpStr.replace(" ","");
            if (showDebug) displayData("Enter2:"+TmpStr+"\r\n"+tv_result.getText().toString());
            PrRecData=TmpStr;
            byte[] keyType=new byte[]{(byte) 0x00, (byte) 0xFF};
            //根据收到的转地址及功能;
            if (paramBytes[3]==keyType[0])
            {
                System.out.println("学习码:"+TmpStr);
                CallAddr="0"+TmpStr.substring(8,13);
                FuncHex="0"+TmpStr.substring(13,14);
                if (showDebug) tv_result.setText("学习码:CallAddr："+CallAddr+"-FuncHex："+FuncHex+"\r\n"+tv_result.getText().toString());
            }
            if (paramBytes[3]==keyType[1])
            {
                System.out.println("固定码:"+TmpStr);
                CallAddr="00"+TmpStr.substring(8,12);
                FuncHex=TmpStr.substring(12,14);
                if (showDebug) tv_result.setText("固定码:CallAddr："+CallAddr+"-FuncHex："+FuncHex+"\r\n"+tv_result.getText().toString());
            }
            studyMessage(CallAddr);
        }

    }

    //接收到呼叫按钮;
    @SuppressLint("Range")
    private void recCall(byte[] paramBytes){
        String CallAddr="",CallNo="",EmpName="",CallType="",FuncHex,NeedCheck="Y",CallColor,FontColor,LightCon;
        System.out.println(paramBytes);
        if (showDebug) displayData("Enter1"+paramBytes.length+"\r\n"+tv_result.getText().toString());
        if (paramBytes.length==9) {
            //ConKey,ConType,NeedCheck;
            String[] rtn=new String[]{"unknow","unknow","unknow","RED","#0000FF","00"};
            String TmpStr=bytesToHexString(paramBytes,paramBytes.length);
            TmpStr=TmpStr.replace(" ","");
            if (showDebug) displayData("Enter2:"+TmpStr+"\r\n"+tv_result.getText().toString());
            PrRecData=TmpStr;
            //呼叫窗口显示着就不再处理;
            if ((callPopupWindow!=null)&&(callPopupWindow.isShowing()==true)) return;
            byte[] keyType=new byte[]{(byte) 0x00, (byte) 0xFF};
            //根据收到的转地址及功能;
            if (paramBytes[3]==keyType[0])
            {
                System.out.println("学习码:"+TmpStr);
                CallAddr="0"+TmpStr.substring(8,13);
                FuncHex="0"+TmpStr.substring(13,14);
                if (showDebug) tv_result.setText("学习码:CallAddr："+CallAddr+"-FuncHex："+FuncHex+"\r\n"+tv_result.getText().toString());
                rtn=getCallType("00",FuncHex);
            }
            if (paramBytes[3]==keyType[1])
            {
                System.out.println("固定码:"+TmpStr);
                CallAddr="00"+TmpStr.substring(8,12);
                FuncHex=TmpStr.substring(12,14);
                if (showDebug) tv_result.setText("固定码:CallAddr："+CallAddr+"-FuncHex："+FuncHex+"\r\n"+tv_result.getText().toString());
                rtn=getCallType("FF",FuncHex);
            }
            if (showDebug) {
                Cursor cursor=mainDB.rawQuery("select * from AndonList",null);
                while (cursor.moveToNext()){
                    String pCallNo=cursor.getString(cursor.getColumnIndex("CallNo"));
                    String pCallAddr=cursor.getString(cursor.getColumnIndex("CallAddr"));
                    String pEmpName=cursor.getString(cursor.getColumnIndex("EmpName"));
                    String pMachType=cursor.getString(cursor.getColumnIndex("MachType"));
                    tv_result.setText(pCallNo+":"+pCallAddr+":"+pEmpName+":"+pMachType+"\r\n"+tv_result.getText().toString());
                }
            }
            //根据处理流程转呼叫记录;
            JSONObject jsonObject=getCallNo(CallAddr);
            if (jsonObject==null) return;
            try {
                CallNo=jsonObject.getString("CallNo");
                EmpName=jsonObject.getString("EmpName");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            CallType=rtn[1];
            NeedCheck=rtn[2];
            CallColor=rtn[3];
            FontColor=rtn[4];
            LightCon=rtn[5];
            String tmpstr="ConKey:"+rtn[0]+" CallAddr:"+CallAddr+" CallNo:"+CallNo+" EmpName:"+EmpName+" CallType:"+CallType+" NeedCheck:"+NeedCheck+" FontColor:"+FontColor;
            System.out.println(tmpstr);
            if (CallNo.length()==0) return;
            //非报到键为呼叫过程
            if (rtn[0].equals("D")==false){
                //检查是否有未处理的，如没有则不处理;
                Cursor cur=mainDB.rawQuery("Select * from CallList where CallNo=? and CallState<2", new String[]{CallNo});
                if (cur.getCount()>0){
                    //重复呼叫
                    showPopWindows(EmpName+"-"+"重复呼叫","Repeat");
                } else {
                    String uuid = UUID.randomUUID().toString().toUpperCase();
                    String StateInfo="待处理";
                    if (NeedCheck.equals("Y")==true) {
                        StateInfo="待报到";
                        //只保存呼叫时间;
                        mainDB.execSQL("Insert into CallList(CallID,CallTime,CallNo,EmpName,CallAddr,CallType,CallState,StateInfo,NeedCheck,CallColor,FontColor,LightCon) values(?,?,?,?,?,?,?,?,?,?,?,?)",
                                new Object[]{uuid, GetCurDateTime(), CallNo,EmpName, CallAddr, CallType, 0, StateInfo,NeedCheck, CallColor,FontColor,LightCon});
                    } else
                    {
                        //直接保存报到时间为呼叫时间;
                        mainDB.execSQL("Insert into CallList(CallID,CallTime,CheckTime,CallNo,EmpName,CallAddr,CallType,CallState,StateInfo,NeedCheck,CallColor,FontColor,LightCon) values(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                new Object[]{uuid, GetCurDateTime(),GetCurDateTime(),CallNo,EmpName, CallAddr, CallType, 0, StateInfo,NeedCheck, CallColor,FontColor,LightCon});
                    }
                    showPopWindows(EmpName+"-呼叫"+CallType,CallColor);
                }
                cur.close();
            }
            //报到键;
            if (rtn[0].equals("D")==true){
                Cursor cur=mainDB.rawQuery("Select * from CallList where CallNo=?  and CallState<2", new String[]{CallNo});
                if (cur.moveToNext()){
                    if (cur.getString(cur.getColumnIndex("StateInfo")).equals("待报到")==true)
                    {
                        mainDB.execSQL("Update CallList Set CallState=1,CheckTime=?,StateInfo=?,Upload=0 where CallID=?",
                                new Object[]{GetCurDateTime(),"待处理" ,cur.getString(cur.getColumnIndex("CallID"))});
                        showPopWindows(EmpName+"-"+"报到成功",CallColor);
                    } else
                    {
                        mainDB.execSQL("Update CallList Set CallState=2,OverTime=?,StateInfo=?,Upload=0 where CallID=?",
                                new Object[]{GetCurDateTime(),"已完成" ,cur.getString(cur.getColumnIndex("CallID"))});
                        showPopWindows(EmpName+"-"+"处理完成",CallColor);
                    }
                }
                cur.close();
            }
            //发消息通知切换到呼叫界面
            Message message = new Message();
            message.what = MSG_SwitchAndon;
            mHandler.removeMessages(message.what);
            mHandler.sendMessage(message);
        }

    }

    //返回遥控器对应的呼叫类型及流程;
    private String[] getCallType(String paramConType,String paramConValue){
        Log.d(TAG,paramConType+"--"+paramConValue);
        String[] rtn=new String[]{"unknow","unknow","unknow","RED","#0000FF","00"};
        if (mCallKeys!=null){
            for (int i=0;i<mCallKeys.size();i++)
            {
                if (mCallKeys.get(i).ConType.equals(paramConType)&&mCallKeys.get(i).ConValue.equals(paramConValue))
                {
                    rtn[0]=mCallKeys.get(i).ConKey;
                    rtn[1]=mCallKeys.get(i).CallType;
                    rtn[2]=mCallKeys.get(i).NeedCheck;
                    rtn[3]=mCallKeys.get(i).CallColor;
                    rtn[4]=mCallKeys.get(i).FontColor;
                    rtn[5]=mCallKeys.get(i).LightCon;
                    break;
                }
            }
        }
        return rtn;
    }

    //返回遥控器对应的呼叫类型及流程;
    private JSONObject getCallNo(String paramCallAddr){
        String paramCallNo,paramEmpName;
        JSONObject jsonObject;
        if (AndonList!=null){
            for (int i=0;i<AndonList.length();i++)
            {
                try {
                    if (AndonList.optJSONObject(i).getString("CallAddr").trim().equals(paramCallAddr.trim()))
                    {
                        paramCallNo=AndonList.optJSONObject(i).getString("CallNo");
                        paramEmpName=AndonList.optJSONObject(i).getString("EmpName");
                        jsonObject=new JSONObject();
                        jsonObject.put("CallNo",paramCallNo);
                        jsonObject.put("EmpName",paramEmpName);
                        return jsonObject;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //控制安东灯
    @SuppressLint("Range")
    private void controlLight(){
        Log.e(TAG,"开灯准备.....");
        if ((mInputStream!=null)&&(mSerialPort!=null)) {
            Log.w(TAG,"开哪个灯........");
            Cursor cur = mainDB.rawQuery("Select * from CallList where CallState=0 order by CallTime", null);
            byte[] cmdBytes;
            if (cur.getCount() == 0) cmdBytes = ConRelayMuti(0xFF, 0x00);
            else {
                cur.moveToNext();
                int v = Integer.valueOf(cur.getString(cur.getColumnIndex("LightCon")), 16);
                cmdBytes = ConRelayMuti(0xFF, v);
            }
            cur.close();
            serialSendBytes(cmdBytes,cmdBytes.length);
        }
    }

    //启动定时器;
    private void startTimer(){
        //启动计时任务;
        int spaceMiSec=switchSpaceSec*1000;
        if (timer == null) {
            timer = new Timer();
        }
        //定时任务;
        if (timetask == null) {
            timetask = new TimerTask() {
                @Override
                public void run() {
                    //也可发消息，由Handler负责统一调度执行;
                    Message message = new Message();
                    message.what =MSG_Switch;
                    mHandler.sendMessage(message);
                }
            };
            Log.e(TAG,"startTimer");
            timer.schedule(timetask, 2000, spaceMiSec);
        }
    }

    //启动定时器;
    private void startUploadTimer(){
        //启动计时任务;
        int spaceMiSec=2000;
        if (uploadTimer == null) {
            uploadTimer = new Timer();
        }
        //定时任务;
        if (uploadTimeTask == null) {
            uploadTimeTask = new TimerTask() {
                @Override
                public void run() {
                    upLoadCallList();
                }
            };
            Log.e(TAG,"startTimer");
            uploadTimer.schedule(uploadTimeTask, 2000, spaceMiSec);
        }
    }
    //上传呼叫记录;
    @SuppressLint("Range")
    private void upLoadCallList() {
        //判断是否有需要上传的记录,未完成的不上传;
        int rtn;
        Cursor cur=mainDB.rawQuery("Select  * from CallList where Upload=0 order by CallTime",null);
        rtn=cur.getCount();
        if (rtn==0) {
            cur.close();
            return;
        }
        if (cur.moveToNext()==true) {
            String CallID,CallTime,CallNo,EmpName,CallAddr,CallType,CallState,StateInfo,CallColor,FontColor,CheckTime,OverTime,NeedCheck;
            CallID=cur.getString(cur.getColumnIndex("CallID"));
            CallTime=cur.getString(cur.getColumnIndex("CallTime"));
            CallNo=cur.getString(cur.getColumnIndex("CallNo"));
            EmpName=cur.getString(cur.getColumnIndex("EmpName"));
            CallAddr=cur.getString(cur.getColumnIndex("CallAddr"));
            CallType=cur.getString(cur.getColumnIndex("CallType"));
            CallState=cur.getString(cur.getColumnIndex("CallState"));
            StateInfo=cur.getString(cur.getColumnIndex("StateInfo"));
            CallColor=cur.getString(cur.getColumnIndex("CallColor"));
            FontColor=cur.getString(cur.getColumnIndex("FontColor"));
            CheckTime=cur.getString(cur.getColumnIndex("CheckTime"));
            OverTime=cur.getString(cur.getColumnIndex("OverTime"));
            NeedCheck=cur.getString(cur.getColumnIndex("NeedCheck"));
            //置值
            String SqlComm="Exec AndonTVUpLoad @BoardNo='" + MainApplication.BoardNo + "',@CallID='"+CallID+ "',@CallNo='"+CallNo+ "',@EmpName='"+EmpName+ "',@CallAddr='"+CallAddr+ "',@CallType='"+CallType
                    + "',@CallTime='"+CallTime+ "',@CheckTime='"+CheckTime+ "',@OverTime='"+OverTime+"',@CallState='"+CallState+ "',@StateInfo='"+StateInfo
                    + "',@CallColor='"+CallColor+ "',@FontColor='"+FontColor+ "',@NeedCheck='"+NeedCheck+"',@OperType='CallList'";
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        }
        cur.close();
    }

    //获取软件版本;
    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    private final Handler mHandler= new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_CheckNetWork:
                    System.out.println("EnterMSG_CheckNetWork");
                    boolean networkState=false;
                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP){
                        networkState=checkNetState_21();
                    }else{
                        networkState=checkNetState_21orNew();
                    }
                    try {
                        if (networkState == true) {
                            stopCheckTimer();
                            ((TextView) findViewById(R.id.tv_NetWork)).setText("网络已连接");
                            ((TextView) findViewById(R.id.tv_NetWork)).setTextColor(getResources().getColor(R.color.transColor));
                            System.out.println(serviceUrl+"/SysConfig.xml");
                            GetServerConfig(serviceUrl+"/SysConfig.xml");
                            //下载最新的版本文件,检查是否需要升级;
                            AutoUpdate autoupdate = new AutoUpdate(mContext,"com.bodacn.andontv");
                            autoupdate.CheckWebUpdate(serviceUrl+"/UPDATE/andontv.xml");
                            //启动时间触发器;
                            startTimer();
                            startUploadTimer();
                        } else {
                            System.out.println("-----------------------------------------CheckNetWork Err-----------------------------------------");
                        }
                    } catch (Exception e){
                        Toast.makeText(findViewById(R.id.tv_NetWork).getContext(),"检查网络状态出错",Toast.LENGTH_LONG).show();
                        startTimer();
                        startUploadTimer();
                    }
                    break;
                case MSG_Switch:
                    if ((curUserPower==null)||(curUserPower.length()==0))
                    {
                        LoadPower(MainApplication.BoardNo);
                    } else {
                        //在学习界面不跳
                        if (mFragments.get(curFragmentIndex).ident == "StudyFragment") return;
                        //执行看看是否需要播放视频
                        if ((PasueSwitch == false)&&(mFragments.size()>0)) {
                            //如果呼叫记录则不跳转;
                            if (GetCallCount()>0){
                                if (mFragments.get(curFragmentIndex).ident!="AndonFragment"){
                                    switchFragment(mContent, "AndonFragment");
                                }
                            } else {
                                if (PushTime == "RUN") {
                                    //bottomLayout.setVisibility(View.GONE);
                                    switchFragment(mContent, "OneFragment");
                                }
                            }
                        }
                    }
                    break;
                case MSG_Init:
                    //根据权限显示按键,同步加载Fragment，不需要的不加;
                    if (curUserPower!=null) {
                        fragmentInit();
                        setHintInfo("",false);
                    }
                    break;
                case MSG_Trans:
                    //发送消息,传递参数;
                    transMessage();
                    break;
                case MSG_SwitchAndon:
                    //在学习界面不跳
                    if (mFragments.get(curFragmentIndex).ident == "StudyFragment") return;
                    if (hasAndonFragment==true) {
                        //开关安东灯;
                        //controlLight();
                        //检查是否有安东数据
                        try {
                            if (curFragmentIndex > -1) {
                                if (GetCallCount() > 0 && mFragments.size() > 0) {
                                    if (mFragments.get(curFragmentIndex).ident != "AndonFragment") {
                                        switchFragment(mContent, "AndonFragment");
                                    }
                                    //发消息,启动某个Fragment Start;
                                    Message message = new Message();
                                    message.what = MSG_Trans;
                                    mHandler.removeMessages(message.what);
                                    mHandler.sendMessage(message);
                                } else {
                                    if (mFragments.get(curFragmentIndex).ident == "AndonFragment") {
                                        jumpNextFragment();
                                    }
                                }
                            }
                        } catch (Exception e){
                            if (showDebug) displayData("出错:"+e.getMessage());
                        }
                    }
                    break;
                case MSG_SerialRecOK:
                    byte[] recBuffer=msg.getData().getByteArray("RecBytes");
                    int recLen=msg.getData().getInt("RecLen");
                    String rechex=msg.getData().getString("RecHex");
                    if (showDebug) displayData(rechex);
                    System.out.println("recBuffer:"+bytesToHexString(recBuffer,recLen));
                    //处理安东
                    if (mFragments.get(curFragmentIndex).ident=="StudyFragment") studyCall(recBuffer);
                    else recCall(recBuffer);
                    break;
                case MSG_GetDataOver:
                    setHintInfo("",false);
                    break;
                case MSG_GetAndonListOver:
                    Bundle bundle=msg.getData();
                    if (showDebug) tv_result.setText("MSG_GetAndonListOver："+bundle.getString("AndonList","未收到"));
                    else {
                        curToast.setText("接收安东列表成功!");
                        curToast.show();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    //API版本23以下时调用此方法进行检测
    //因为API23后getNetworkInfo(int networkType)方法被弃用
    public boolean checkNetState_21(){
        try {
            //步骤1：通过Context.getSystemService(Context.CONNECTIVITY_SERVICE)获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
            //NetworkInfo对象包含网络连接的所有信息
            //步骤3：根据需要取出网络连接信息
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Boolean isWifiConn = networkInfo.isConnected();
            //获取移动数据连接的信息
            networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            Boolean isMobileConn = networkInfo.isConnected();
            System.out.println("Wifi是否连接:" + isWifiConn + " 移动数据是否连接:" + isMobileConn);
            return isWifiConn || isMobileConn;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21",Toast.LENGTH_LONG).show();
            return false;
        }
    }

    //API版本23及以上时调用此方法进行网络的检测
    //步骤非常类似
    public boolean checkNetState_21orNew(){
        //获得ConnectivityManager对象
        boolean isConnect=false;
        try {
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络连接的信息
            Network[] networks = new Network[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                networks = connMgr.getAllNetworks();
            }
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    networkInfo = connMgr.getNetworkInfo(networks[i]);
                }
                if (isConnect == false) isConnect = networkInfo.isConnected();

            }
            return isConnect;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21orNew",Toast.LENGTH_LONG).show();
            return false;
        }
    }


    //跳转到下一Fragment;
    private void jumpNextFragment() {
        //处理一些事务;
        curFragmentIndex++;
        //只自动转到非安东呼叫页面;
        if (curFragmentIndex >= mFragments.size()) {
            curFragmentIndex = 0;
            if ((mFragments.size()>1)&&(mFragments.get(curFragmentIndex).ident=="AndonFragment"))
            {
                curFragmentIndex++;
            }
        }
        System.out.println("切换至" + (curFragmentIndex + 1) + "页......");
        if (mFragments.size()>1) switchFragment(mContent, mFragments.get(curFragmentIndex).ident);
    }


    //根据权限初始化Fragment;
    private void fragmentInit(){
        hasAndonFragment=false;
        if (GetUserFuncPower("Andon")==1) {
            AddFragment("AndonFragment");
            hasAndonFragment=true;
        }
        if (GetUserFuncPower("One")==1) {
            AddFragment("OneFragment");
        }
        if (GetUserFuncPower("Study")==1) {
            AddFragment("StudyFragment");
        }
        if (GetUserFuncPower("UpdateAndon")==1) {
            LoadAndonList(MainApplication.BoardNo);
            LoadConDefine(MainApplication.BoardNo);
        }
        loadDefaultFragment();
        //发消息,启动某个Fragment Start;
        Message message = new Message();
        message.what = MSG_Trans;
        mHandler.removeMessages(message.what);
        mHandler.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG,"----------------onDestroy------------------");
        //停止计时任务;
        stopTimer();
        stopUploadTimer();
        closeSerialPort();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG,"----------------onPause------------------");
        stopTimer();
        stopUploadTimer();
    }


    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
    }
    //停止计时器;
    private void stopUploadTimer(){
        if (uploadTimer != null) {
            uploadTimer.cancel();
            uploadTimer = null;
        }
        if (uploadTimeTask != null) {
            uploadTimeTask.cancel();
            uploadTimeTask = null;
        }
    }

    private void showMemu() {
        stopTimer();
        //打开配置页面;
        Intent i=new Intent(MainActivity.this,SettingsActivity.class);
        startActivity(i);

    }

    //根据顺序预加载Fragment
    private void loadDefaultFragment(){
        curFragmentIndex=-1;
        if (mFragments.size()>0) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Log.d("msg", "Add Fragment------------------------《预加载》");
            for (int i = mFragments.size() - 1; i >= 0; i--) {
                curFragmentIndex = i;
                Log.d("预加载", mFragments.get(curFragmentIndex).ident);
                mContent = mFragments.get(curFragmentIndex).frgmt;
                fragmentTransaction.add(R.id.mFragmentContainer, mContent);
                fragmentTransaction.hide(mContent);
            }
            //提交修改并显示;
            fragmentTransaction.show(mContent);
            fragmentTransaction.commit();
        }
        //发消息判断是否需要切换非安东界面;
        Message message = new Message();
        message.what = MSG_SwitchAndon;
        mHandler.removeMessages(message.what);
        mHandler.sendMessage(message);
    }

    //Fragment切换
    public void switchFragment(Fragment from, String toFrgmtName) {
        Fragment to=null;
        for (int i=0;i<mFragments.size();i++)
        {
            if (mFragments.get(i).ident.equals(toFrgmtName)==true)
            {
                to=mFragments.get(i).frgmt;
                curFragmentIndex=i;
                break;
            }
        }
        if ((mContent != to)&&(to!=null)) {
            mContent = to;
            FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(
                    android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(from).add(R.id.mFragmentContainer, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
        //发消息,启动某个Fragment Start;
        Message message = new Message();
        message.what = MSG_Trans;
        mHandler.removeMessages(message.what);
        mHandler.sendMessage(message);

    }

    //传送消息;
    private void transMessage() {
        //发送消息给Fragment;
        Log.d("SendParam", "sendParamFragment-----["+curFragmentIndex+"]-------------1;");
        if (curFragmentIndex<0) return;
        mParams.clear();
        mParams.put("ParamComm", "ParamValue");
        mParams.put("ServiceUrl", serviceUrl+serverUrlExt);
        mParams.put("ServiceDir", serviceUrl);
        mParams.put("BoardNo", MainApplication.BoardNo);
        mParams.put("SpaceSec", refreshSpaceSec);
        mParams.put("SwitchCount",switchCount);
        mParams.put("RunState", "TRUE");
        mParams.put("PushTime", PushTime);
        mParams.put("FragmentIndex", curFragmentIndex);
        if (mFragments.size()>0) {
            if (mFragments.get(curFragmentIndex).ident.equals("AndonFragment")==true)
                if (transAndonParamsListener != null) transAndonParamsListener.TransParams(mParams);
            if (mFragments.get(curFragmentIndex).ident.equals("OneFragment")==true)
                if (transOneParamsListener != null) transOneParamsListener.TransParams(mParams);

        }
        Log.d("SendParam", "sendParamFragment-----["+curFragmentIndex+"]-------------2;");
    }

    //传送消息;
    private void studyMessage(String paramCallAddr) {
        //发送消息给Fragment;
        Log.d("SendParam", "sendParamFragment-----["+curFragmentIndex+"]-------------1;");
        if (curFragmentIndex<0) return;
        mParams.clear();
        mParams.put("ParamComm", "CallAddr");
        mParams.put("ParamValue", paramCallAddr);
        if (transStudyParamsListener != null) transStudyParamsListener.TransParams(mParams);
    }

    /**
     * 定义一个Handler用于接收Fragment给Activity发出来的指令
     */
    public Handler mainHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                switch (msg.what) {
                    case msgOneFragment:
                        break;
                    case msgTwoFragment:
                        break;
                    case msgThreeFragment:
                        break;
                    case msgFourFragment:
                        break;
                    default:
                        break;
                }
            }
        }
    };

    //初始化
    private void initView()
    {
        findViewById(R.id.testBtn).setOnClickListener(this);
        mainLinerLayout=findViewById(R.id.mainLinerLayout);
        mFragmentContainer=findViewById(R.id.mFragmentContainer);
        bottomLayout=findViewById(R.id.bottomLayout);
        liner_debugInfo=findViewById(R.id.liner_debugInfo);
        liner_debugBtn=findViewById(R.id.liner_debugBtn);
        if (showDebug==true) {
            liner_debugInfo.setVisibility(View.VISIBLE);
            liner_debugBtn.setVisibility(View.VISIBLE);
        } else
        {
            liner_debugInfo.setVisibility(View.GONE);
            liner_debugBtn.setVisibility(View.GONE);
        }
        tv_boardNo=findViewById(R.id.tv_boardNo);
        tv_hintInfo=findViewById(R.id.tv_hintInfo);
        tv_hintInfo.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                DropAllTable();
                CreateDBTable();
                curToast.setText("数据重建成功!");
                curToast.show();
                return false;
            }
        });
        MenuBtn= findViewById(R.id.MenuBtn);
        AndonBtn=findViewById(R.id.AndonBtn);
        ClearBtn=findViewById(R.id.ClearBtn);
        OneBtn=  findViewById(R.id.OneBtn);
        TwoBtn=  findViewById(R.id.TwoBtn);
        ThreeBtn=  findViewById(R.id.ThreeBtn);
        FourBtn=  findViewById(R.id.FourBtn);
        CallBtn=findViewById(R.id.CallBtn);
        StudyBtn=findViewById(R.id.StudyBtn);
        StudyBtn.setOnClickListener(this);
        MenuBtn.setOnClickListener(this);
        AndonBtn.setOnClickListener(this);
        ClearBtn.setOnClickListener(this);
        OneBtn.setOnClickListener(this);
        TwoBtn.setOnClickListener(this);
        ThreeBtn.setOnClickListener(this);
        FourBtn.setOnClickListener(this);
        CallBtn.setOnClickListener(this);
        /*
        MenuBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    MenuBtn.setBackgroundResource(R.color.transColor);
                }else {
                    MenuBtn.setBackgroundResource(R.drawable.frameline_background);
                }
            }
        });
        */
        pgbar_wait=findViewById(R.id.pgbar_wait);
        //蓝牙测试
        tv_result=findViewById(R.id.tv_result);
        tv_data = findViewById(R.id.tv_data);
        tv_portname=findViewById(R.id.tv_portname);
        tv_portstate=findViewById(R.id.tv_portstate);
        //消息提示框
        curToast=Toast.makeText(this,"测试",Toast.LENGTH_SHORT);

    }

    //获取权限,默认都有;
    private int GetUserFuncPower(String paramFunc){
        if (curUserPower.length()>0)
        {
            for (int i=0;i<curUserPower.length();i++){
                if (curUserPower.optJSONObject(i).has(paramFunc)==true)
                {
                    try {
                        return curUserPower.optJSONObject(i).getInt(paramFunc);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            return 0;
        }
        return 1;
    }

    //加载需要用到的Fragment
    private boolean AddFragment(String paramFrgmtName){
        //创建Fragment;
        FragmentStruct tmpFrgmtStruct=new FragmentStruct();
        try {
            Log.d("AddFragment",paramFrgmtName+"--Start");
            tmpFrgmtStruct.frgmt=(Fragment) Class.forName(getPackageName()+"."+paramFrgmtName).newInstance();
            tmpFrgmtStruct.ident=paramFrgmtName;
            mFragments.add(tmpFrgmtStruct);
            Log.d("AddFragment",paramFrgmtName+"--Over");
            return true;
        }catch (ClassNotFoundException err){
            err.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return  false;//未成功加载
    }
    //获取看板权限，显示几页由这个决定;
    private void LoadPower(String boardNo) {
        try {
            curUserPower=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG,"读取看板权限");
        //执行SQL过程
        String SqlComm="Exec LookBoardTV @BoardNo='" + boardNo + "',@OperType='Power'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        displayData("正在获取看板权限....");
        setHintInfo("正在获取看板权限....",true);
    }

    //设置状态条
    private void setHintInfo(String paramInfo, Boolean paramShowProcBar){
        tv_hintInfo.setText(paramInfo);
        if (paramShowProcBar==true) pgbar_wait.setVisibility(View.VISIBLE);
        else pgbar_wait.setVisibility(View.GONE);
    }

    //获取遥控器定义;
    private void LoadAndonList(String boardNo) {
        try {
            AndonList=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e(TAG,"正在获取看安东列表");
        displayData("正在获取看安东列表....");
        //执行SQL过程
        String SqlComm="Exec LookBoardTV @BoardNo='" + boardNo + "',@OperType='AndonList'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        setHintInfo("正在获取看安东列表....",true);
    }

    //获取遥控器定义;
    private void LoadConDefine(String boardNo) {
        Log.e(TAG,"读取遥控器定义权限");
        displayData("读取遥控器定义权限....");
        //执行SQL过程
        String SqlComm="Exec LookBoardTV @BoardNo='" + boardNo + "',@OperType='ConDefine'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        setHintInfo("正在获取看遥控器定义....",true);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    System.out.println(jsonArray);
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true)
                        {
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("Power")==true)
                            {
                                if (jsonArray.optJSONObject(0).has("UserPower")==true) curUserPower=new JSONArray(jsonArray.optJSONObject(0).getString("UserPower"));
                                //也可发消息，由Handler负责统一调度执行;
                                Message message = new Message();
                                message.what = MSG_Init;
                                mHandler.removeMessages(message.what);
                                mHandler.sendMessage(message);
                            }
                            //获取安东列表;
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("ConDefine")==true) {
                                //删除原有的;
                                mainDB.execSQL("Delete from ConDefine");
                                mCallKeys.clear();
                                if ((jsonArray.optJSONObject(0).has("ConType")==true)
                                        &&(jsonArray.optJSONObject(0).has("ConValue")==true)
                                        &&(jsonArray.optJSONObject(0).has("ConKey")==true)
                                        &&(jsonArray.optJSONObject(0).has("CallType")==true)
                                        &&(jsonArray.optJSONObject(0).has("NeedCheck")==true)) {
                                    //更新相关表暂存本地;
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        //加表定义列表中
                                        CallKeyDefine KeyDefine=new CallKeyDefine();
                                        KeyDefine.ConType=jsonArray.optJSONObject(i).getString("ConType");
                                        KeyDefine.ConValue=jsonArray.optJSONObject(i).getString("ConValue");
                                        KeyDefine.ConKey=jsonArray.optJSONObject(i).getString("ConKey");
                                        KeyDefine.CallType=jsonArray.optJSONObject(i).getString("CallType");
                                        KeyDefine.CallColor=jsonArray.optJSONObject(i).getString("CallColor");
                                        KeyDefine.FontColor=jsonArray.optJSONObject(i).getString("FontColor");
                                        KeyDefine.NeedCheck=jsonArray.optJSONObject(i).getString("NeedCheck");
                                        KeyDefine.LightCon=jsonArray.optJSONObject(i).getString("LightCon");
                                        mCallKeys.add(KeyDefine);
                                        //插入新的;
                                        mainDB.execSQL("Insert into ConDefine (ConType,ConValue,ConKey,CallType,CallColor,FontColor,NeedCheck,LightCon) Values(?,?,?,?,?,?,?,?)",
                                                new Object[]{jsonArray.optJSONObject(i).getString("ConType")
                                                        ,jsonArray.optJSONObject(i).getString("ConValue")
                                                        ,jsonArray.optJSONObject(i).getString("ConKey")
                                                        ,jsonArray.optJSONObject(i).getString("CallType")
                                                        ,jsonArray.optJSONObject(i).getString("CallColor")
                                                        ,jsonArray.optJSONObject(i).getString("FontColor")
                                                        ,jsonArray.optJSONObject(i).getString("NeedCheck")
                                                        ,jsonArray.optJSONObject(i).getString("LightCon")});
                                    }
                                }
                            }
                            //获取安东列表;
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("AndonList")==true) {
                                AndonList = jsonArray;
                                if (jsonArray.optJSONObject(0).has("DataOper")==true) {
                                    //表示要先清除所有;
                                    if (jsonArray.optJSONObject(0).getString("DataOper").equals("Delete")){
                                        mainDB.execSQL("Delete from  AndonList");
                                    }
                                }
                                if ((jsonArray.optJSONObject(0).has("CallNo")==true)
                                        &&(jsonArray.optJSONObject(0).has("CallAddr")==true)
                                        &&(jsonArray.optJSONObject(0).has("EmpName")==true)
                                        &&(jsonArray.optJSONObject(0).has("MachType")==true)) {
                                    //更新相关表暂存本地;
                                    for (int i = 0; i < AndonList.length(); i++) {
                                        System.out.println("保存呼叫器列表"+i);
                                        //删除原有的;
                                        mainDB.execSQL("Delete from AndonList where CallAddr=?",new Object[]{AndonList.optJSONObject(i).getString("CallAddr")});
                                        //插入新的;
                                        mainDB.execSQL("Insert into AndonList (CallNo,CallAddr,Empname,MachType) Values(?,?,?,?)",
                                                new Object[]{AndonList.optJSONObject(i).getString("CallNo")
                                                        ,AndonList.optJSONObject(i).getString("CallAddr")
                                                        ,AndonList.optJSONObject(i).getString("EmpName")
                                                        ,AndonList.optJSONObject(i).getString("MachType")});
                                    }
                                }
                                //也可发消息，由Handler负责统一调度执行;
                                Message message = new Message();
                                Bundle bundle=new Bundle();
                                bundle.putString("AndonList",AndonList.toString());
                                message.what = MSG_GetAndonListOver;
                                message.setData(bundle);
                                mHandler.removeMessages(message.what);
                                mHandler.sendMessage(message);

                            }
                            //安东上传完成;
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("CallList")==true){
                                if (jsonArray.optJSONObject(0).has("CallID")==true)
                                {
                                    if (jsonArray.optJSONObject(0).has("UpLoad")==true)
                                    {
                                        if (jsonArray.optJSONObject(0).getInt("UpLoad")==1)
                                        {
                                            Log.w(TAG,"更新对应呼叫记录....");
                                            mainDB.execSQL("Update CallList Set UpLoad=1 where CallID=?",new Object[]{jsonArray.optJSONObject(0).getString("CallID")});
                                            Cursor cur=mainDB.rawQuery("Select * from  CallList where UpLoad=0 or CallState<2",null);
                                            if (cur.getCount()==0){
                                                Log.e(TAG,"清空呼叫列表....");
                                                clearCallList();//清空呼叫表;
                                            }
                                            cur.close();
                                        }
                                    }
                                }
                            }
                            //也可发消息，由Handler负责统一调度执行;
                            Message message = new Message();
                            message.what = MSG_GetDataOver;
                            mHandler.removeMessages(message.what);
                            mHandler.sendMessage(message);

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }





    private void displayData(String data) {
        if ((data != null)&showDebug) {
            tv_data.setText(data);
            if (showDebug) {
                if (tv_result.getLineCount() > 100) tv_result.setText("");
                tv_result.setText("接收:" + data + "\r\n" + tv_result.getText().toString());
            }

        }
    }

    //板卡继电器控制函数(单路);
    private byte[] ConRelaySingle(int paramAddr, int paramPlac, int paramLight){
        byte[] conBytes = new byte[7];
        conBytes[0]=(byte)paramAddr;
        conBytes[1]=0x0A;
        conBytes[2]=0x02;
        conBytes[3]=(byte)paramPlac;
        conBytes[4]=(byte)paramLight;
        int crc=getCRC(conBytes,5);
        conBytes[5]=(byte)(crc/256);//CRC高位
        conBytes[6]=(byte)(crc%256);//CRC低位
        return conBytes;
    }
    //板卡继电器控制函数(多路);
    private byte[] ConRelayMuti(int paramAddr, int paramLightBit){
        //paramLightBit=0x0F全亮，0x00全灭;
        byte[] conBytes = new byte[6];
        conBytes[0]=(byte)paramAddr;
        conBytes[1]=0x08;
        conBytes[2]=0x06;
        conBytes[3]=(byte)paramLightBit;
        int crc=getCRC(conBytes,4);
        conBytes[4]=(byte)(crc/256);//CRC高位
        conBytes[5]=(byte)(crc%256);//CRC低位
        return conBytes;
    }

    //发送消息;
    public static void serialSendBytes(byte[] paramBytes,int paramSize) {
        FileOutputStream mOutputStream;
        byte[] sendBytes= new byte[paramSize];
        for (int i=0;i<paramSize;i++) sendBytes[i]=paramBytes[i];
        String tmpCmdStr;
        if (mSerialPort!=null) {
            try {
                mOutputStream = (FileOutputStream) mSerialPort.getOutputStream();
                tmpCmdStr=bytesToHexString(sendBytes,paramSize);
                Log.d("SEND-Start", tmpCmdStr);
                mOutputStream.write(sendBytes);
                Thread.sleep(6);
                Log.d("SEND-Over", tmpCmdStr);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打开串口的方法
     */
    public void openSrialPort(){
        Log.i("调试输出","打开串口");
        try {
            tv_portname.setText(portName);
            Log.i("调试输出","打开串口1");
            //创建串口2;
            if (mSerialPort!=null) mSerialPort.close();
            Log.i("调试输出","打开串口2");
            //速率9600,无校验;
            mSerialPort = new SerialPort(new File(portName), 9600,0,8,1);
            Log.i("调试输出","打开串口3");
            if (mSerialPort!=null) {
                Log.i("调试输出","打开串口4");
                if (mInputStream != null) mInputStream.close();
                mInputStream = (FileInputStream) mSerialPort.getInputStream();
                receiveFlag = true;
                tv_portstate.setText("打开");
            }

            //receiveSerialPort();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *关闭串口的方法
     * 关闭串口中的输入输出流
     * 然后将flag的值设为flag，终止接收数据线程
     */
    public void closeSerialPort(){
        Log.i("调试输出","关闭串口");
        try {
            receiveFlag = false;
            if (mSerialPort!=null)  {
                mSerialPort.close();
                if(mInputStream != null) {
                    mInputStream.close();
                    mInputStream=null;
                }
                mSerialPort=null;
            }
            tv_portstate.setText("关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}
